<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/19
 * Time: 20:41
 */
namespace app\api\controller;

use app\common\controller\Api;
use function GuzzleHttp\Psr7\uri_for;
use think\Db;

/**
 * 测试调用
 */
class Test extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = [];
    // 返回数据无需加密的方法,单个设置例如：['test','test2'],*表示全部,只对 $this->success()方法有效
    protected $noEncryption = '*';
    // 接收的数据无需解密的方法(只有调用Api类中的getpm()方法有效),单个设置例如：['test','test2'],*表示全部,只对 $this->getpm()方法有效
    protected $rNoEncryption = [];

    /**
     * 到时完成
     */
    public function confirm_order(){
        require ROOT_PATH . '/confirmorder.php';
    }

    /**
     * 到时取消
     */
    public function lose_order(){
        require ROOT_PATH . '/loseorder.php';
    }

    public function test(){
        echo "<pre>";
        $redis = rds();
        $day = date('Ymd');
        $t = $redis->hGetall(REDIS_PREFIX.'user_tz');
        $sy = $redis->hGetall(REDIS_PREFIX.'user_sy');
        $day = $redis->hGetall(REDIS_PREFIX.$day.'_sy');
        $pv = $redis->hGetall(REDIS_PREFIX.'user_pv');
        $pv_bili = $redis->hGetall(REDIS_PREFIX.'user_pv_bili');
        $share = $redis->hGetall(REDIS_PREFIX.'user_share_award');

//        foreach($t as $v=>$ts){
//            $add_sy = $ts*0.01/8640;
//            echo $v.'---'.$ts.' 静态奖励增加 ='.$add_sy."\r\n";
//            echo '缓存静态收益='.($sy[$v]+$add_sy)."\r\n";
//        }
        var_dump($t,$sy,$day,$pv,$pv_bili,$share);
    }
    public function test2() {
        $time_start =  strtotime(date('Y-m-d', strtotime('-1 monday', time())));
        $time_end = time();
        $users = \db('user')
            ->alias('u')
            ->field('u2.tronAddr,ud.tjid,count(u.id) as team_sum, u2.pv_sum as sum_order')
            ->join('user_detail ud', 'u.id = ud.uid')
            ->join('user u2', 'u2.id = ud.tjid','left')
            ->where('u.createtime','between',[$time_start, $time_end])
            ->where(['u.credit1'=>['>',0]])
            ->group('ud.tjid')
            ->order('team_sum desc')
            ->limit(10)
            ->select();
        var_dump(\db()->getLastSql());
        var_dump($users);
    }
    public function fre() {
        $prefix = config('database.prefix');
        $tz_frozen = [
            '35' => 0.1,
            '36' => 0.1,
            '33' => 0.1,
            '1' => 100,
        ];
        //释放三层冻结资金
        if ($tz_frozen) {
            $fz_release_arr = [];
            $bi_arr = [10, 5, 2]; //三层比例
            $fz_uids = implode(',',array_keys($tz_frozen));
            $fz_users = \db('user_detail')->whereIn('uid',$fz_uids)->column('uid,tjstr,tjdept','uid');
            if ($fz_users) {
                foreach ($fz_users as $fz_k => $fz_value) {
                    $fz_tjstr = explode(',',$fz_value['tjstr']);
                    if (empty($tz_frozen[$fz_k])) continue;
                    for ($i = 0; $i < 3; $i++) {
                        if (empty($fz_tjstr[$i])) continue;
                        $profit = $tz_frozen[$fz_k] * $bi_arr[$i] / 100;
                        $fz_release_arr[$fz_tjstr[$i]] = ($fz_release_arr[$fz_tjstr[$i]] ?? 0) + $profit;
                        echo "=======用户投资{$tz_frozen[$fz_k]}id:{$fz_k},冻结资产释放 ".bcadd($i,1)."代 ID:{$fz_tjstr[$i]}  释放金额：{$profit}========"."\r\n";
                    }
                }
            }

            $fz_release_uids = implode(',',array_keys($fz_release_arr));
            $fz_sum_users = \db('user')->whereIn('id',$fz_release_uids)->column('frozen_sum,credit2','id');

            $update_fz_sql = "";
            $update_credit2_sql = "";

            foreach ($fz_sum_users as $k => $v) {
                if (empty($v['frozen_sum'])) continue;
                if ($v['frozen_sum'] >= $fz_release_arr[$k]) {
                    $t_profit = $fz_release_arr[$k];
                } else {
                    $t_profit = $v['frozen_sum'];
                }
                $update_fz_sql .= " when id = {$k} then frozen_sum - {$t_profit}";
                $update_credit2_sql .= " when id = {$k} then credit2 + {$t_profit}";
            }

            if($update_fz_sql || $update_credit2_sql){
                $update_fz = " frozen_sum = (case {$update_fz_sql} else frozen_sum end)";
                $update_fz .= ",credit2 = (case {$update_credit2_sql} else credit2 end)";
            }
            try {
                \db()->execute("UPDATE {$prefix}user SET ".trim($update_fz,','));
                echo '=======投资释放冻结资产成功'.date('Y-m-d H:i:s')."===========\r\n";
            } catch (\Exception $exception) {
                echo '=======投资释放冻结资产失败：'.$exception->getMessage().date('Y-m-d H:i:s')."===========\r\n";
            }
        }
    }
    public function t1() {
        $res = \db()->execute("UPDATE fa_user SET frozen_sum =  where id = -1");
        var_dump($res);
    }
    public function delhase(){
        $redis = rds();
        $where = [
            'type' => 0,
            'status' => 1,
            'isout' => 0,
        ];
        $orders = \db('tron_order')->where($where)->whereBetween('createtime','1605878100,1606098480')->column('id,uid,type,amt,txid','id');
        var_dump($orders);

    }

    public function reGrantSy(){
        $redis = rds();
        $d = date('Ymd');
        $errs = $redis->hGetAll('error_sy');
        echo "<pre>";
        var_dump($errs);
        foreach($errs as $user_id => $sy){
            $lua = <<<LUA
            local user_id = KEYS[1]
            local day_sy_key = KEYS[2]
            local add_sy = ARGV[1]
            local tz = redis.call('hGet','user_tz',user_id)
            if tz ~= false
            then
                tz = tz*1
                if tonumber(tz) > 0
                then
                    local day_sy = redis.call('hGet',day_sy_key,user_id)
                    add_sy = add_sy*1
                    if day_sy == false
                    then
                        redis.call('hIncrByFloat','user_sy',user_id,add_sy)
                        redis.call('hIncrByFloat',day_sy_key,user_id,add_sy)
                    else
                        local new_sy = day_sy + add_sy
                        local max_sy = tz*0.1
                        day_sy = day_sy*1
                        if tonumber(day_sy) < tonumber(max_sy)
                        then
                            if tonumber(new_sy) <= tonumber(max_sy)
                            then
                                redis.call('hIncrByFloat','user_sy',user_id,add_sy)
                                redis.call('hIncrByFloat',day_sy_key,user_id,add_sy)
                            else
                                local add_sy = max_sy - day_sy
                                redis.call('hIncrByFloat','user_sy',user_id,add_sy)
                                redis.call('hSet',day_sy_key,user_id,max_sy)
                            end
                        end
                    end
                end
            end
            return true
LUA;
            $res = $redis->eval($lua,[$user_id,$d.'_sy',$sy],2);
            if($res === false){
                echo $user_id.'失败!!!';
            }else{
                echo $user_id.'成功!!!';
                $redis->hDel('error_sy',$user_id);
            }
        }
    }

}